<template>
  <el-row :gutter="16">
    <el-col :span="6">
      <el-card style="height: 500px">
        <div class="head-con">
          <div class="head-core">
            <el-upload
              class="head-upload"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="{ Authorization: authStore.getToken() }"
            >
              <PictureComponent ref="headPhoto" :picUrl="userLabel!.headImgUrl" :previewEnabled="false" pictureHeight="100px" />
              <!-- <el-image
                class="p-img"
                v-if="headImgUrl != null && headImgUrl != '' && headImgUrl.length > 10"
                fit="contain"
                :src="headImgUrl"
                :preview-teleported="true"
              >
                <template #error>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
              </el-image>
              <el-image
                v-else
                style="height: 28px; margin-right: 10px"
                fit="contain"
                :src="noPicSrc"
              ></el-image> -->
            </el-upload>
          </div>
          <span class="p-nickname">
            {{ userLabel!.nickName }}
          </span>
          <ul class="p-list-ul">
            <li>
              <span class="p-li-icon">
                <el-icon><User /></el-icon>
              </span>
              <span class="p-li-name">
                {{ person.position }}
              </span>
            </li>
            <li>
              <span class="p-li-icon">
                <el-icon><School /></el-icon>
              </span>
              <span class="p-li-name">
                {{ person.school }}
              </span>
            </li>
            <li>
              <span class="p-li-icon">
                <el-icon><Location /></el-icon>
              </span>
              <span class="p-li-name">
                {{ person.address }}
              </span>
            </li>
            <li>
              <span class="p-li-icon">
                <el-icon><Tickets /></el-icon>
              </span>
              <span class="p-li-name">
                {{ person.teaching }}
              </span>
            </li>
          </ul>
          <hr style="height: 1px; border: none; border-top: 1px dashed rgba(105, 105, 105, 0.3)" />
          <template v-for="t in tags" :key="t">
            <el-tag class="mr-2" type="info">{{ t }}</el-tag>
          </template>
        </div>
      </el-card>
    </el-col>
    <el-col :span="18">
      <el-card style="height: 500px">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="账户信息" name="User" class="demo-tab"></el-tab-pane>
        </el-tabs>
        <div class="p-input">
          <FormComponent
            ref="formRef"
            formLabelWidth="120px"
            formTitle="账户"
            v-model="userForm!"
            :formHeader="formHeader"
            :formRules="rules"
            :formUrl="urls.API_URL_BACKSTAGE_LOGINUSER"
            formAction="put"
            @afterFormSubmitSuccess="afterSubmitSuccess"
            @afterFormReset="afterReset"
          >
            <!-- <template #[aa]="scope"> 11</template> -->
            <!-- 下面代码是用于调试在自定义组件中双向绑定时的参数是否正常
          <template #nickName="scope">
              <el-input
                v-model="userForm!['nickName']"
                type="text"
                :placeholder="`${scope.item.placeholder ? scope.item.placeholder : scope.item.label}`"
                clearable
              />
            </template> -->
          </FormComponent>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
// const aa = 'nickName';
//20240812最后更新，此处的图片上传方式可以作为范例（本地显示、远程显示两种方式）。
import PictureComponent from '@/components/base/other/PictureComponent.vue';
import FormComponent from '@/components/base/table/form/FormComponent.vue';
import { userSexDict } from '@/api/dict';
import { nextTick, onBeforeMount, onMounted, reactive, ref } from 'vue';
import type { FormInstance, TabsPaneContext, UploadProps } from 'element-plus';
import urls from '@/api/request/urls';
import { useAuthStore } from '@/stores/auth';
import type { User } from '@/types/interface/auth_interface';
import { ElMessage } from 'element-plus';
import { updateSession } from '@/api/mes/page/authority/user/index';
import type { FormHeader } from '@/types/interface/base_interface';
// 默认选中标签页
const activeName = ref('User');

// 切换标签页时触发
const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event);
};

const authStore = useAuthStore();
// 用户表单信息
const userForm = ref<User | undefined>({});
//用户标签
const userLabel = ref<User | undefined>({});
// 展示用户信息，死数据
const person = ref({
  position: '资深教师',
  school: '柳州城市职业学院',
  address: '柳州',
  teaching: 'HTML、VUE、CSS'
});
const tags = ref(['热情', '上进', '教学经验丰富', '实践能力强']);
// 用户头像
// const headImgUrl = ref<string>('');
// 上传头像地址
const uploadUrl = ref(urls.API_URL_BACKSTAGE_USER_UPLOAD_PERSON_PHOTO);

//定义上传头像组件
const headPhoto = ref();
// 上传头像方法
const handleAvatarSuccess: UploadProps['onSuccess'] = async (response, uploadFile) => {
  if (response.success) {
    //如果上传成功
    userLabel.value!.headImgUrl = URL.createObjectURL(uploadFile.raw!); //将图片变为已经上传的图片。注意：从本地图片读取而不是服务端
    // 获取当前登录账户信息，并存储到store，同时要拷贝避免修改表单值且未提交服务端前会影响登录账户的值
    userForm.value = { ...(await authStore.getLoginUserFromRemote()) };
    //获取store中的信息
    userLabel.value = authStore.getLoginUser();
    //下面的方式也可以显示图片，不同的是，下面的方式是显示服务器图片。上面的方式是显示本地的图片。
    // if (user.value != null) {
    //   headImgUrl.value = user.value.headImgUrl!;
    //   //刷新头像，因为同名所以要刷新
    //   headPhoto.value.fresh();
    // }
  } else {
    ElMessage.error(response.msg);
  }
};

// 表单元素
const formHeader = ref<FormHeader[]>([
  {
    label: '账户名',
    prop: 'username'
  },
  {
    label: '昵称',
    prop: 'nickName'
  },
  {
    label: '性别',
    prop: 'sex',
    type: 'select',
    list: userSexDict
  },
  {
    label: '描述',
    prop: 'description',
    placeholder: '请输入账户的描述',
    type: 'textarea'
  }
]);
// 表单验证规则
const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入账户名',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 10,
      message: '账户名长度必须在3-10个字符之间',
      trigger: 'blur'
    }
  ],
  nickName: [
    {
      required: true,
      message: '请输入昵称',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 10,
      message: '昵称长度必须在3-10个字符之间',
      trigger: 'blur'
    }
  ]
});
// 定义表单的对象
const formRef = ref<FormInstance>();
//如果表单提交成功，回调函数
const afterSubmitSuccess = async () => {
  // 获取当前登录账户信息，并存储到store，同时要拷贝避免修改表单值且未提交服务端前会影响登录账户的值
  userForm.value = { ...(await authStore.getLoginUserFromRemote()) };
  //获取store中的信息
  userLabel.value = authStore.getLoginUser();
};
//重置功能
const afterReset = async () => {
  //获取store中的信息
  userForm.value = { ...userLabel.value };
};
onMounted(async () => {
  // 获取当前登录账户信息，并存储到store，同时要拷贝避免修改表单值且未提交服务端前会影响登录账户的值
  userForm.value = { ...(await authStore.getLoginUserFromRemote()) };
  //获取store中的信息
  userLabel.value = authStore.getLoginUser();
});
</script>

<style scoped>
/*定义左边用户信息展示框的宽高*/
.head-con {
  width: 100%;
  height: 100%;
}

/*设置用户头像，并使其居中显示*/
.head-core {
  text-align: center;
}

/*设置用户头像呈圆角，并加鼠标移上事件*/
/* .p-img {
  border-radius: 50%;
  cursor: pointer;
} */

/*设置用户昵称样式*/
.p-nickname {
  width: 100%;
  text-align: center;
  display: inline-block;
  margin-top: 20px;
  font-weight: bold;
  font-size: 1.3em;
}

/*设置用户信息样式*/
.p-list-ul {
  width: 100%;
  margin-top: 30px;
  padding: 0;
  display: inline-block;
}

.p-list-ul li {
  list-style: none;
  margin-top: 10px;
}

.p-li-icon {
  margin-right: 20px;
}

.p-li-name {
  font-size: 0.9em;
  height: 40px;
}

/*设置用户个人标签展示样式*/
.mr-2 {
  margin-right: 10px;
}

.p-input {
  margin-top: 2%;
}

.p-form-item {
  margin-top: 3%;
  width: 500px;
}

/*设置右边标签页样式*/
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 45px;
  font-weight: 600;
}
</style>
